import { debounce } from './debounce';
import _404JPG from '$lib/empty/nopic.png';

/**
 * 判断图片地址是否有效
 */
export function isImgUrl(url: string) {
	const img = new Image();
	img.src = url;

	return new Promise((resolve) => {
		img.onload = () => {
			resolve(true);
		};
		img.onerror = () => {
			resolve(false);
		};
	});
}

export function lazyLoadImages(selector = '.lazy-load', options = {}) {
	const defaultOptions = {
		root: null,
		rootMargin: '0px',
		threshold: 0.5 // 0.5 means 50% of the element is visible
	};
	const observer = new IntersectionObserver(
		(entries) => {
			entries.forEach((entry) => {
				if (entry.isIntersecting) {
					const img = entry.target;
					const src = img.getAttribute('data-src') as string;
					if (!src) return img.setAttribute('src', _404JPG);
					isImgUrl(src).then((isUseFull) => {
						img.setAttribute('src', isUseFull ? src : _404JPG);
						observer.unobserve(img);
					});
				}
			});
		},
		{ ...defaultOptions, ...options }
	);
	const images = document.querySelectorAll(selector);
	images.forEach((i) => observer.observe(i));

	const cancelObserver = () => {
		observer.disconnect();
	};

	return cancelObserver;
}

export const debounce_lazy_load_images = debounce(lazyLoadImages, 500);
